using System;
using System.Collections.Generic;
using System.Text;
using Un4seen.Bass;
using Un4seen.Bass.Misc;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using Un4seen.Bass.AddOn.Enc;

namespace NtpChat.Client.Model
{
    public class RecordUtil
    {
        private RECORDPROC myRecordProc;
        private int stream = -1;
        private int playbackStream = -1;
        byte[] myBuffer = null;


        public event SendBufferHandler SendBuffer;        
        public delegate void SendBufferHandler(byte[] buffer, int length);

        public void Init()
        {
            Bass.BASS_RecordInit(-1);
            Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_8BITS, 
                IntPtr.Zero, null);
        }

        public void Initialize()
        {
            Init();
            Record();
        }

        public void Record()
        {
            myRecordProc = new RECORDPROC(MyRecording);

            stream = Bass.BASS_RecordStart(44100, 1, 
                BASSFlag.BASS_RECORD_PAUSE, 500, myRecordProc, IntPtr.Zero);
            playbackStream = Bass.BASS_StreamCreatePush(44100, 1, 
                BASSFlag.BASS_DEFAULT, IntPtr.Zero);
        }

        

        private bool MyRecording(int handle, IntPtr buffer, 
            int length, IntPtr user)
        {
            if(SendBuffer != null)
            {
                if(myBuffer == null || myBuffer.Length < length)
                    myBuffer = new byte[length];
                Marshal.Copy(buffer, myBuffer, 0, length);
                SendBuffer(myBuffer, length);
            }
            return true; 
        }

        public void PlayBuffer(byte[] buffer)
        {
            if (buffer.Length == 0)
                return;

            Bass.BASS_StreamPutData(playbackStream, buffer, buffer.Length);
        }

        public void Play()
        {
            Bass.BASS_ChannelPlay(stream, false);
            Bass.BASS_ChannelPlay(playbackStream, false);
        }

        public void Stop()
        {
            Bass.BASS_ChannelStop(stream);
            Bass.BASS_ChannelStop(playbackStream);
        }

        public void Free()
        {
            if (stream != -1 && playbackStream != -1)
            {
                Bass.BASS_StreamFree(stream);
                Bass.BASS_StreamFree(playbackStream);
            }
        }

        ~RecordUtil()
        {
            Free();
            Bass.BASS_RecordFree();
            Bass.BASS_Free();
        }
    }
}
